// 导入 mongoose 模块
const mongo = require("mongoose");

// 连接 mongodb 数据库
mongo.connect("mongodb://127.0.0.1:27017/bilibili");

// 设置回调
mongo.connection.once("open", () => {
  // 创建文档结构对象
  let bookSchema = new mongo.Schema({
    name: {
      type: String,
      required: true,
      unique: true,
    },
    author: {
      type: String,
      default: "匿名",
    },
    category: {
      type: String,
      enum: ["言情", "鬼怪", "武侠"],
    },
    price: {
      type: Number,
    },
  });

  // 创建模型
  let bookModel = mongo.model("books", bookSchema);

  // 新增文档
  bookModel.create({
    name: "哈利波特",
    // author: "abc",
    price: 77.8,
    category: "鬼怪",
  });
  console.log("连接成功");
});

mongo.connection.on("error", () => {
  console.log("连接失败");
});

mongo.connection.on("close", () => {
  console.log("连接关闭");
});
